import {
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
  useImperativeHandle,
  forwardRef,
  Ref,
} from 'react';
import { Select } from 'antd';
import { getTableList, getTableInfo, getTableInfoApi } from '../../designer/webServer/services';
import useDebounce from './hook';
import { connect } from '@formily/react';
import { multilingualFormat, useEvents } from '@inbiz/utils';
import { defaultProps } from '../../designer/schema';
import api from './api';
import { toJS } from '@formily/reactive';
import styles from './index.less';
import { getMessage, TextWidget } from '@inbiz/react';
import { useInbizData, requestInbizData } from '@inbiz/hooks';
import { arrRepeat, existIndataSource, removeHtmlTag, valueFormat } from '../common/util';
import { IProps } from '../interfaces';
import DynamicListTable from './components/DynamicListTable';
import {uniqBy} from 'lodash'

const Option = Select.Option;

type IRef = Ref<ReturnType<typeof api>>;

const EformDynamicList: EFC<IProps, any> = forwardRef((props: IProps, ref: IRef) => {
  const [configEvents] = useEvents(props.callBackEvents, props.emit);
  // 选中的值
  const [selectValue, $selectValue] = useState<string[] | string | null>(null);
  // 是否多选
  const [selectType, $selectType] = useState<boolean>(false);
  // 选项动态options
  const [options, $options] = useState<any[]>([]);
  // 表格loading
  const [loadding, $loading] = useState<boolean>(false);
  // 表格显示数据
  const [dataSource, $dataSource] = useState<any[]>([]);
  // 是否通过扩展代码设置dataSource
  const [codeSetDataSource, $codeSetDataSource] = useState(false);
  // ref 存储dataSource
  const refDataSource = useRef<any>([]);
  //ref 存储默认的dataSource
  const DefaultSource = useRef<any>([]);
  // 表格数据总量
  const [total, $total] = useState<number>(0);
  // 当前页码
  const [current, $current] = useState<number>(1);
  // 分页量
  const [pageSize, $pageSize] = useState<number>(props.showconfig?.pageSize || 5);
  // 搜索值
  const [searchIpt, $searchIpt] = useState<string>('');
  // 会否是初始化
  const [isInit, $isInit] = useState<boolean>(true);
  // 搜索字段
  const [searchField, $searchField] = useState<any[]>([]);
  // 下拉浮层显示状态
  const [show, $show] = useState(false);
  // 组件唯一class
  const listClass = useState(`inbiz-eform-dynamic-list-select-box-${new Date().valueOf()}`);

  // 屏蔽关闭浮层时搜索值变空触发接口调用状态
  const init = useRef<any>();
  // 上次搜索值(通过current存储)
  const searRef = useRef<any>();
  // 搜索后未清关闭阻止调接口
  const stopGet = useRef<any>(false);
  // 上一次value
  const before = useRef<any>(null);
  // onload执行控制
  const initStatus = useRef<boolean>(true);
  // 下拉框option的外层div
  const memuRef = useRef<HTMLDivElement | null>(null);
  // 下拉组件
  const selectRef = useRef<any>();
  const SelectDiv = useRef<any>();

  // 防抖后的搜索值
  const searchStatus = useDebounce(searchIpt, 500);
  //存储字段
  const storageField =
    props.showconfig?.storageField || props?.primarykey || 'id';
  // 显示字段
  const showField: string = props.showconfig?.selectName?.replace('.', '$') || '';
  // 表格显示数据
  const list = props.showconfig?.list;
  // 记录选中数据的详情
  const selectData = useRef<any[]>([]);

  useEffect(() => {
    // 修复bug 400， 有默认值重置时， 数据显示为id
    if (
      isInit === false &&
      refDataSource.current?.length &&
      options.length === 0 &&
      (Array.isArray(props.value) ? props.value.length : props.value)
    ) {
      const newlist = (Array.isArray(props.value) ? props.value : [props.value])
        .map((item) => {
          const findData = refDataSource.current?.find((data: { [x: string]: any }) => {
            return data?.[storageField] == item;
          });
          if (!findData) {
            return;
          }
          return {
            value: findData[storageField].toString(),
            label: findData[showField],
          };
        })
        .filter((item) => !!item);
      if (newlist?.length) {
        $options(newlist);
      }
     
    }
  }, [isInit, props.value, options]);

  useImperativeHandle(
    ref,
    () => ({
      ...api(
        configEvents,
        {
          list: selectValue,
          optionRef: refDataSource,
          $option: setData,
          props,
          showField,
          getServerData,
          searchField,
          storageField,
          selectData: selectData.current
        }
      ),
    }),
    [selectValue, props, options, refDataSource, showField, storageField, DefaultSource, props.value],
  );

  // 初始化空值调用onload
  useEffect(() => {
    if (!props.value || (Array.isArray(props.value) && !props.value.length)) {
      if (initStatus.current) {
        props.emit?.('onload');
        initStatus.current = false;
      }
    }
  }, []);

  // 设置搜索字段
  useEffect(() => {
    if (props.showconfig) {
      let config = props.showconfig;
      let arr: any[] = [];
      let list = config.list;
      if (Array.isArray(list) && list.length) {
        list.map((item) => {
          if (item.SelectText) {
            const field = item.YsField.includes('$') ? item.YsField.split('$')[1] : item.YsField;
            arr.push({
              model: item.modelName,
              field,
            });
          }
        });
      }
      $searchField(arr);
    }
  }, [props.showconfig]);

  // 初始化默认值
  useEffect(() => {
    props.selecttype ? $selectValue([]) : $selectValue(null);
    $selectType(props.selecttype || false);
  }, [props.selecttype]);

  // 处理选中数据，保留数据详情，以便通过扩展方法获取
  useEffect(() => {
    const { value } = props;
    if (value === undefined || value === null || !value?.length) {
      return;
    }
    if (Array.isArray(value)) {
      selectData.current = selectData.current.filter(item => value.includes(item?.[storageField]));
      value.forEach(v => {
        const isHas = selectData.current.some(item => item?.[storageField] === v);
        if (!isHas) {
          const data = dataSource.find(el => el?.[storageField] === v);
          if (data) {
            selectData.current.push(data);
          }
        }
      });
    } else {
      const data = dataSource.find(el => el?.[storageField] === value);
      if (data) {
        selectData.current = [data];
      }
    }
  }, [props.value])

  // 监听防抖后的搜索值变化-查询数据
  useEffect(() => {
    if (stopGet.current) {
      stopGet.current = false;
      return;
    }
    $current(1);
    search(1);
  }, [searchStatus]);

  // 值变化
  useEffect(() => {
    let value = toJS(props.value);
    let beforeValue = before.current;
    // 设置值
    if (String(value) !== String(before.current)) {
      before.current = value;
      defaultInit().then((res) => {
        // 触发select事件
        if (!isInit && props.value !== undefined) {
          beforeValue = Array.isArray(beforeValue)
            ? beforeValue
            : beforeValue
              ? beforeValue?.toString().split(',')
              : [];
          if (Array.isArray(props.value)) {
            let list: any[] = [];
            if (value.length > beforeValue.length) {
              list = value.filter((item: any) => {
                return beforeValue?.indexOf(item) === -1;
              });
            } else {
              list = beforeValue?.filter((item: any) => {
                return value?.indexOf(item) === -1;
              });
            }
            props.emit?.(
              'onSelect',
              list[0],
              value.length > beforeValue?.length,
              refDataSource.current?.filter((item: any) => item?.[storageField] == list[0])[0],
            );
          } else {
            if (props.value == null) {
              props.emit?.(
                'onSelect',
                beforeValue,
                false,
                refDataSource.current?.filter((item: any) => item[storageField] == beforeValue)[0],
              );
            } else {
              props.emit?.(
                'onSelect',
                props.value,
                true,
                refDataSource.current?.filter(
                  (item: any) => item?.[storageField] == props.value,
                )[0],
              );
            }
          }
        }
      });
    }
  }, [props.value, isInit]);

  // 表格显示字段Columns
  const columns = useMemo(() => {
    if (Array.isArray(list)) {
      let newList = [...list];
      if (newList.length) {
        let maxWidth = SelectDiv?.current?.clientWidth || 500;
        let allWidth = props.selecttype ? 62 : 30;
        newList.map((item) => {
          allWidth += Number(item.Width);
        });
        let doms = document.getElementsByClassName(listClass);
        if (doms.length && doms[0].clientWidth > 500) {
          maxWidth = doms[0].clientWidth;
        }
        if (allWidth < maxWidth) {
          newList.push({
            YsField: '',
            Value: ' ',
            Text: ' ',
            Width: maxWidth - allWidth,
            SelectText: '',
            modelName: '',
          });
        }
      }
      return newList.map((item) => ({
        title: getMessage(item.Text && item.Text !== '' ? item.Text : item.Value),
        key: item.Value.replace('.', '$'),
        dataIndex: item.Value.replace('.', '$'),
        width:
          !item.Width || item.Width === '' || Number.isNaN(Number(item.Width))
            ? 100
            : Math.round(Number(item.Width)),
        ellipsis: {
          showTitle: true,
        },
        render: (val: any) => (
          <span>
            {val !== undefined && val !== null
              ? typeof val === 'boolean'
                ? String(val)
                : removeHtmlTag(val)
              : ' '}
          </span>
        ),
      }));
    }
    return [];
  }, [list, props.selecttype, initStatus.current, show]);

  // 兼容老版查询sourceModel
  const searchSourceModel = useMemo(() => {
    if (!props?.sourceModel) return;
    if (typeof props.sourceModel === 'string') {
      return props.sourceModel
    }
    if ('searchData' in props.sourceModel) {
      return props.sourceModel.searchData
    }
  }, [props.sourceModel]);

  // 兼容老版编辑sourceModel
  const editSourceModel = useMemo(() => {
    if (!props?.sourceModel) return;
    if (typeof props.sourceModel === 'string') {
      return props.sourceModel
    }
    if ('editData' in props.sourceModel) {
      return props.sourceModel.editData
    }
  }, [props.sourceModel]);

  // 查询获取数据详情
  const { runAsync: searchRunAsync } = useInbizData(
    () => {
      if (typeof searchSourceModel === 'string') {
        return {
          service: ({
            appId,
            ...params
          }) => {
            return getTableList({
              appId,
              ...params
            });
          },
        };
      } else {
        return searchSourceModel;
      }
    },
    {
      initialData: [],
      configEvents
    }
  );

  // 编辑获取数据详情
  const { runAsync: editRunAsync } = useInbizData(
    () => {
      if (props.sourcetype === 'model') {
        return {
          service: ({
            appId,
            ...params
          }) => {
            return getTableInfo({
              appId,
              ...params
            });
          },
        };
      } else {
        if (typeof editSourceModel === 'string') {
          return {
            service: ({
              appId,
              ...params
            }) => {
              return getTableInfoApi({
                appId,
                ...params
              });
            },
          };
        } else {
          return editSourceModel;
        }
      }
    },
    {
      eventKeys: ['onTextParamFormat', 'onTextRequest', 'onTextData'],
      initialData: [],
      configEvents
    }
  );

  // 默认值处理
  const defaultInit = useCallback(async () => {
    let list = props.showconfig?.list;
    if ((!list || !Array.isArray(list) || !list.length) && !props.value) {
      return;
    }
    let isSelectValue = false;
    if (dataSource?.length && props.value !== undefined) {
      const valueArr = Array.isArray(props.value) ? props.value : [props.value];
      const datas = valueArr.map(item => {
        return [...selectData.current, ...dataSource].find(fitem => fitem[storageField] === item)
      }).filter(item => !!item);
      if (datas.length === valueArr.length) {
        isSelectValue = true;
      }
    }
    if (
      isInit ||
      (!existIndataSource(props.value, dataSource, selectValue, storageField) && !codeSetDataSource) ||
      (props.value !== undefined && props.value?.toString() != selectValue?.toString()) &&
      !isSelectValue
    ) {
      let value: any = props.value || props.value == 0 ? props.value : '';
      if (Array.isArray(value)) {
        value = value.toString();
      }
      if (value && value !== '') {
        let data =
          props.sourcetype === 'api'
            ? {
              appId: props.inbiz?.appInfo?.appId || '',
              id: value,
              key: editSourceModel || '',
              iConditions: {},
            }
            : {
              appId: props.inbiz?.appInfo?.appId || '',
              ids: value,
              queryKey: editSourceModel || '',
              field: props.showconfig?.storageField,
            };
        if (typeof editSourceModel == 'object') {
          data = {
            id: value
          }
        }
        let _res = await editRunAsync(data);
        if (_res && !Array.isArray(_res.Rows)) {
          _res.Rows = [_res.Rows];
        }
        const showField = props.showconfig?.selectName || '';
        const arr: any[] = [];
        if (_res && Array.isArray(_res.Rows) && _res.Rows.length && _res.Rows[0]) {
          _res.primary &&
            _res.Rows.map((item: any) => {
              if (!item[storageField]) {
                item[storageField] = item[_res.primary];
              }
            });
          const opts = _res.Rows.map((item: any) => {
            arr.push(String(item?.[storageField]));
            return {
              value: String(item?.[storageField]),
              label: multilingualFormat(item?.[showField]),
            };
          });
          if (props.selecttype) {
            // 存储字段不是唯一值可能出现的情况 则取第一个
            if (arrRepeat(arr)) {
              $selectValue(arr[0]);
              $options([opts[0]]);
            } else {
              $selectValue(arr);
              $options(opts);
            }
          } else {
            $selectValue(arr[0]);
            $options(opts);
          }
          let list = _res.Rows.map((item: any) => {
            let newItem = item;
            newItem[storageField] = String(newItem[storageField]);
            return newItem;
          });
          refDataSource.current = _res.Rows;
          DefaultSource.current = _res.Rows;
          selectData.current = _res.Rows;
          if (!dataSource.length) {
            $dataSource(list);
          }
          // $dataSource(list);
        } else {
          const exist = existIndataSource(props.value, refDataSource.current, selectValue, storageField);
          let value = valueFormat(props.value);
          const opts = uniqBy([...refDataSource.current, ...(dataSource || [])]
              ?.filter((data: any) => value.includes(data?.[storageField]))
              .map((item: any) => {
                return {
                  value: String(item?.[storageField]),
                  label: item?.[showField],
                };
              }), 'value') || [];
          if (props.selecttype) {
            $options(opts);
            $selectValue(exist ? value : []);
          } else {
            $options(opts);
            $selectValue(exist ? value : null);
          }
        }
        if (initStatus.current) {
          props.emit?.('onload');
          initStatus.current = false;
        }
        $isInit(false);
      } else {
        if (props.selecttype) {
          $selectValue([]);
        } else {
          $selectValue(null);
        }
        $isInit(false);
      }
    } else {
      // 展开面板后 通过扩展代码设置value options会为空数组
      if (options.length) {
        let value = valueFormat(props.value);
        const opts = uniqBy([...refDataSource.current, ...(dataSource || [])] 
          .filter((data: any) => value.includes(data[storageField]))
          .map((item: any) => {
            return {
              value: item?.[storageField],
              label: item?.[showField],
            };
          }), 'value');
        $options(opts);
      }
      $selectValue(props.value);
    }
  }, [props.value, isInit, dataSource, options, selectValue, codeSetDataSource, props.showconfig]);

  // 扩展代码loadData设置数据源内容
  const setData = useCallback(
    (list: any[], isOptions) => {
      // props.selecttype ? $selectValue([]) : $selectValue(null);
      // $options(list);
      list = list.map((item: any) => {
        let newItem = item;
        newItem[storageField] = String(newItem[storageField]);
        return newItem;
      });
      refDataSource.current = list;
      init.current = false;
      $dataSource(list);
      $codeSetDataSource(true);
      $total(list?.length || 0)
      if (isOptions) {
        $options(list);
      }
    },
    [props.selecttype],
  );

  // 扩展代码getServerData请求接口获取data
  const getServerData = useCallback(async (params) => {
    const { pageSize, pageNumber, search = '' } = params;
    return await getTablesList({
      pageSize: pageSize || 10,
      pageNumber: pageNumber || 1,
      search: search || '',
      getData: true,
    });
  }, []);

  // 查询列表数据-真实接口调用
  const getTablesList = useCallback(
    async (params: {
      pageSize: number;
      pageNumber: number;
      search?: string;
      getData?: boolean;
    }) => {
      const { pageSize, pageNumber, search = '' } = params;
      let arr: any[] = [...searchField];
      let group: {
        index: number;
        connector: 0 | 1;
        condition: {
          connector: 0 | 1;
          field: string;
          modelName?: string;
          operator:
          | 'eq'
          | 'neq'
          | 'gt'
          | 'get'
          | 'lt'
          | 'lte'
          | 'like'
          | 'nlike'
          | 'nstartwith'
          | 'startwith'
          | 'endwith'
          | 'nendwith';
          value?: unknown;
        }[];
      }[] = [];
      arr.map((item, idx) => {
        group.push({
          index: idx,
          connector: 1,
          condition: [
            {
              connector: 1,
              modelName: item.model || '',
              field: item.field || '',
              operator: 'like',
              value: search,
            },
          ],
        });
      });
      let data =
        props.sourcetype === 'api'
          ? {
            appId: props.inbiz?.appInfo?.appId || '',
            key: searchSourceModel || '',
            iConditions: {
              pageIndex: pageNumber,
              pageSize,
              search,
            },
          }
          : {
            appId: props.inbiz?.appInfo?.appId || '',
            key: searchSourceModel || '',
            pageInfo: {
              index: pageNumber,
              size: pageSize,
            },
            conditions: search.trim() === '' ? [] : group,
          };
      if (typeof searchSourceModel == 'object') {
        data = {
          ...data.iConditions
        }
      }
      if (props.sourcetype != 'api' && !data.key && !configEvents.current.onRequest) {
        $loading(false);
        return;
      }
      return new Promise((reslove) => {
        searchRunAsync(data)
          .then((res) => {
            if (res && res.Rows && res.Rows.length) {
              const lists = { ...res };
              props.emit?.('onSuccess', lists);
              lists.Rows = lists.Rows.map((item: any) => {
                if (!item[storageField] && lists.primary && lists.primary !== '') {
                  item[storageField] = item[lists.primary];
                }
                //修复数据中存在多语言时
                Object.keys(item).forEach(key => {
                  item[key] = multilingualFormat(item[key])
                });
                return item;
              });
              $total(lists.Total);
              let list = Array.isArray(lists.Rows) ? lists.Rows : [];
              list = list.map((item: any) => ({
                ...item,
                id: String(item.id),
              }));
              if (params.getData) {
                reslove(list);
              }
              refDataSource.current = list;
              list = list.map((item: any) => {
                let newItem = item;
                 Object.keys(newItem).forEach((key)=>{
                  if(newItem[key]?.includes?.('{multilingual}global')){
                    newItem[key]= getMessage(newItem[key])
                  }
                 })
                newItem[storageField] = String(newItem[storageField]);
                return newItem;
              });
              $dataSource(list);
              $loading(false);
            } else {
              $total(0);
              refDataSource.current = [];
              $dataSource([]);
              $loading(false);
            }
          })
          .catch(() => {
            props.emit?.('onError');
            $total(0);
            refDataSource.current = [];
            $dataSource([]);
            $loading(false);
          });
      });
    },
    [searchField],
  );

  // 根据场景发起搜索
  const search = useCallback(
    (idx: number, size?: number) => {
      if (!init.current) {
        init.current = true;
        return;
      }
      if (!columns || !Array.isArray(columns) || !columns.length) {
        return;
      }
      // 记录当前搜索值
      searRef.current = searchStatus;
      let muck = size ? size : pageSize;
      getList(idx, muck, searchStatus);
    },
    [pageSize, searchStatus, columns],
  );

  // 搜索值变化
  const onSearch = (val: string) => {
    $searchIpt(val.trim());
  };

  // 删除单项
  const onDeselect = useCallback(
    (key) => {
      if (selectType && Array.isArray(selectValue)) {
        let arr = selectValue.filter((item) => item !== key);
        props.onChange && props.onChange(arr);
      } else {
        // 存储字段不是唯一性的时候取第一个值则不为数组 此时清空所有值
        props.onChange && props.onChange([]);
      }
    },
    [selectValue, selectType],
  );

  // 单选清除数据
  const onClear = useCallback(() => {
    if (!selectType) {
      props.onChange && props.onChange(null);
      // props.emit?.('onSelect', selectValue, false, options[0]);
      $options([]);
    }
  }, [selectType, selectValue, options]);

  // 查询列表数据
  const getList = (num: number, size: number, searchTxt: string = '') => {
    $loading(true);
    getTablesList({
      pageSize: size,
      pageNumber: num,
      search: searchTxt,
    });
  };

  // 下拉面板高度
  const dropdownHeight = useMemo(() => {
    let height = 228;
    if (props.dropdownHeight) {
      height = props.dropdownHeight - 61;
      if (dataSource.length) {
        height -= 40;
      }
    }
    if (height <= 0) {
      height = 37;
    }
    return height;
  }, [props.dropdownHeight, dataSource]);

  const dropdownStyle = useMemo(() => {
    return props?.componentIsInline
      ? {
        maxWidth: `${SelectDiv?.current?.clientWidth}px` || '500px',
        minWidth: `${SelectDiv?.current?.clientWidth}px`,
      }
      : {
        maxWidth: `${SelectDiv?.current?.clientWidth}px` || '500px',
      };
  }, [props?.componentIsInline]);

  // 查看模式
  let showText: any[] = []
  if (options && props.viewMode == 'look') {
    options.forEach((item: any) => {
      showText.push(item.label)
    })
  }


  return (
    <div ref={SelectDiv}>
      {props.viewMode == 'look' ? showText.toString() :
        <Select
          onSearch={onSearch}
          onDeselect={onDeselect}
          onClear={onClear}
          ref={selectRef}
          disabled={props.readOnly || props.disabled}
          value={selectValue}
          mode={selectType ? 'multiple' : undefined}
          showSearch
          showArrow
          allowClear={!selectType}
          autoClearSearchValue={false}
          placeholder={<TextWidget>{props.placeholder}</TextWidget>}
          className={`${styles['inbiz-eform-dynamic-list-select-box']} ${listClass}`}
          dropdownClassName={styles['inbiz-eform-dynamic-list-select-down']}
          dropdownStyle={dropdownStyle}
          dropdownMatchSelectWidth={false}
          onDropdownVisibleChange={(e) => {
            $show(e);
            props.emit?.('onDropdownVisibleChange', e);
            if ((props.autoLoading === undefined || props.autoLoading) && e && !codeSetDataSource) {
              $current(1);
              search(1);
            } else if (searchIpt !== '') {
              $searchIpt('');
              stopGet.current = true;
            }
          }}
          dropdownRender={(menu) => {
            return (
              <DynamicListTable
                menu={menu}
                selectType={selectType}
                columns={columns}
                dataSource={dataSource}
                total={total}
                current={current}
                pageSize={pageSize}
                loadding={loadding}
                storageField={storageField}
                selectValue={selectValue}
                options={options}
                showField={showField}
                memuRef={memuRef}
                selectRef={selectRef}
                scroll={{
                  x: SelectDiv?.current?.clientWidth - 30 || 470,
                  y: dropdownHeight,
                }}
                $options={$options}
                $current={$current}
                $pageSize={$pageSize}
                $searchIpt={$searchIpt}
                search={search}
                {...props}
              />
            );
          }}
        >
          {options.map((item) => (
            <Option value={item.value} key={`${item.value}-${item.label}`}>
              {item.label}
            </Option>
          ))}
        </Select>
      }
    </div>
  );
});

EformDynamicList.displayName = 'EformDynamicList';

(
  EformDynamicList as typeof EformDynamicList & IDefaultValueFormat<typeof defaultProps>
).defaultValueFormat = async (props: any): Promise<string | void | string[]> => {
  let value: string = '';
  const storageField = props.showconfig?.storageField || 'id';
  const editSourceModel = typeof props.sourceModel === 'string' ? props.sourceModel : props.sourceModel?.editData;
  if (props.defaulttype == 'custom' && props.default && props.default.trim() !== '') {
    // 去空格、去重处理
    let arr = props.default.split(',');
    arr = arr.map((item: any) => item.trim());
    arr = [...new Set(arr)];
    value = arr.join(',');
  } else if (props.defaulttype == 'system' && props.systemDefaultValue) {
    const { inbiz } = props;
    const { userInfo } = inbiz;
    const data = {
      System_Var_LoginUserID: userInfo?.guid,
      System_Var_LoginUserIdentityID: userInfo?.id,
      System_Var_LoginUserName: userInfo?.memberName,
      System_Var_LoginUserDeptID: userInfo?.deptId,
      System_Var_LoginUserDeptName: userInfo?.deptName,
      System_Var_LoginUserPostID: userInfo?.positonId,
      System_Var_LoginUserPostName: userInfo?.positionName,
      System_Var_LoginUserAccount: userInfo?.loginName,
    };
    for (const key in data) {
      if (key == props.systemDefaultValue) {
        value = data[key];
      }
    }
  }
  if (editSourceModel && value !== '') {
    let data1 = {
      appId: props.inbiz?.appInfo?.appId || '',
      id: value,
      key: editSourceModel || '',
      iConditions: {},
    };
    let data2 = {
      appId: props.inbiz?.appInfo?.appId || '',
      ids: value,
      queryKey: editSourceModel || '',
      field: storageField,
    };
    const request = requestInbizData(
      () => {
        return editSourceModel;
      },
      {},
      props.inbiz
    );
    let res;
    if (typeof editSourceModel === 'object') {
      data1 = {
        id: value
      }
      res = await request(data1);
    } else {
      res = props.sourcetype === 'api' ? await getTableInfoApi(data1) : await getTableInfo(data2);
    }
    // 接口合法验证l
    if (!res || !res.Rows) {
      return;
    }
    if (res && !Array.isArray(res.Rows)) {
      res.Rows = [res.Rows];
    }
    if (res && Array.isArray(res.Rows) && res.Rows.length) {
      const newArr: any[] = [];
      res.primary &&
        res.Rows.map((item: any) => {
          if (!item[storageField]) {
            item[storageField] = item[res.primary];
          }
        });
      res.Rows.map((item: any) => {
        newArr.push(String(item[storageField]));
      });
      if (props.selecttype) {
        return newArr;
      } else if (newArr.length) {
        // 找出默认值字符串中的第一个合法值
        let list = value ? `${value}`.split(',') : [];
        let key = newArr[0];
        for (let i = 0; i < list.length; i++) {
          if (newArr.includes(Number(list[i]))) {
            key = list[i];
            break;
          }
        }
        return key;
      }
    }
  }
};

export default connect(EformDynamicList);
